<?php
/**
 * Created by PhpStorm.
 * User: maskerj
 * Date: 2017/7/27
 * Time: 下午4:48
 * 首页模型
 */
require_once $_SERVER["DOCUMENT_ROOT"]."/vendor/autoload.php";
use MongoDB\BSON\ObjectID;
use MongoDB\Client;

class Index_model extends CI_Model{
    private $mongoConn;  //mongodb链接

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    /**
     * 初始化Mongodb链接
     */
    private function initMongoConn(){
        $this->config->load('mongodb');
        $mongoConfig = $this->config->item('mongo_db')['default'];
        $this->mongoConn = new Client($mongoConfig['hostname'].':'.$mongoConfig['port'],[
            "username" => $mongoConfig['username'],
            "password" => $mongoConfig['password'],
            'authSource' => $mongoConfig['authSource']
        ]);
    }

    /**
     * 统计系统状态
     * @return array
     */
    public function countSysStatus(){
        //查询对接系统数,集合数
        $sysNum = $this->db->select('id')->from('system_db')->get()->num_rows();
        $colNum = $this->db->select('id')->from('collection')->get()->num_rows();

        //组合 系统和集合名称
        $sysAndCol = $this->db->select('sd.system,collection.col_name')
            ->from('system_db as sd')
            ->join('collection','collection.dbID = sd.id')
            ->get()->result_array();
        $this->initMongoConn();
        //统计对接数据总量
        $dataNum = 0;
        foreach ($sysAndCol as $one) {
            $mongoCol = $this->mongoConn->selectDatabase($one['system'].'_db')->selectCollection($one['col_name']);
            $dataNum += $mongoCol->count();
        }
        //统计接口运行状态
        $successNum = 0;
        $failedNum  = 0;
        //查询所有数据库名
        $syaArr = $this->db->select('dbname,system')->from('system_db')->get()->result_array();
        foreach ($syaArr as $sys) {
            $configCol = $this->mongoConn->selectDatabase($sys['dbname'])->selectCollection('config');
            foreach ($sysAndCol as $one){
                if($one['system'] == $sys['system']){
                    $interfaceStatus = $configCol->findOne([
                        '_collection_name'  => $one['col_name']
                    ]);
                    if($interfaceStatus['_auth_status'] == 'success'){
                        $successNum++;
                    }else{
                        $failedNum++;
                    }
                }

            }
        }

        return [
            'sysNum'    => $sysNum,
            'colNum'    => $colNum,
            'dataNum'   => $dataNum,
            'successNum'=> $successNum,
            'failedNum' => $failedNum
        ];
    }
}